
import { setDefaultStudentList, updateStudent, addStudent, deleteStudent, setDefaultStudent } from '../../../../services/students/studentData';
import Toast from 'tdesign-miniprogram/toast/index';
import { getStudentsPromise } from '../edit/util';
import Dialog from 'tdesign-miniprogram/dialog/index';
import { getSelectedSchoolId, setStudentsList, getStudentsList, getSchoolList } from '../../../../userData/userData';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    studentsList: [],
    deleteID: '',
    showDeleteConfirm: false,
    isOrderSure: false,
  },
  /** 选择模式 */
  selectMode: false,
  /**
   * 生命周期函数--监听页面加载
   */
  onShow() {
    this.init()
  },
  onLoad(options) {
    const { selectMode = '', isOrderSure = '', id = '' } = options;
    this.setData({
      isOrderSure: !!isOrderSure,
      id,
    });
    this.selectMode = !!selectMode;

  },
  init() {
    this.getStudentsList();
  },
  getStudentsList() {
    const list = getStudentsList()
    this.setData({
      studentsList: list
    })
    this.studentsListSort()
  },

  deleteStudentHandle(e) {
    const { _id } = e.detail;
    console.log(e)
    if (this.data.studentsList.length == 1 || e.detail.default == 1) {
      Toast({
        context: this,
        selector: '#t-toast',
        message: '该小孩已被首页选中不能被删除',
        icon: '',
        duration: 2000,
      });
      return
    }
    const dialogConfig = {
      context: this,
      title: '确认要删除吗？',
      content: '删除当前子女信息购物车选中孩子物品将被删除！',
      confirmBtn: '确定',
      cancelBtn: '取消',
    };
    console.log(e.detail)
    Dialog.confirm(dialogConfig)
      .then(() => {
        deleteStudent(_id).then((student) => {
          this.setData({
            studentsList: this.data.studentsList.filter((student) => student._id !== _id)
          })
          setStudentsList(this.data.studentsList)
        })
      })
      .catch(() => console.log('点击了取消'))
      .finally(() => Dialog.close());

  },
  editStudentHandle({ detail }) {
    this.waitForNewStudents();

    const { _id } = detail || {};
    wx.navigateTo({ url: `/pages/usercenter/students/edit/index?id=${_id}` });
  },
  selectHandle({ detail }) {
    if (this.selectMode) {
      this.hasSelect = true;
      setDefaultStudent(detail._id).then((student) => {
      })
      let studentsList = [...this.data.studentsList];
      studentsList.forEach(element => {
        if (element._id == detail._id) {
          setDefaultStudentList(element._id, element.i_id, () => {
          });
          element.default = 1
        }
        else {
          element.default = 0
        }
      });
      wx.navigateBack({ delta: 1 });
      setStudentsList(studentsList)
      this.studentsListSort()

    } else {
      this.editStudentHandle({ detail });
    }
  },

  createHandle() {
    this.waitForNewStudents();
    wx.navigateTo({ url: '/pages/usercenter/students/edit/index' });
  },

  waitForNewStudents() {
    getStudentsPromise()
      .then((newStudents) => {
        let studentsList = [...this.data.studentsList];
        if (newStudents._id == 0) {
          addStudent(newStudents).then((student) => {
            const schoolDate = getSchoolList()
            student.result[0].schoolName = schoolDate[student.result[0].i_id].name
            studentsList.push(student.result[0]);
            this.setData({
              studentsList
            });
            setStudentsList(studentsList)
            this.studentsListSort();
          })

        } else {
          updateStudent(newStudents).then((student) => {

          })
          studentsList = studentsList.map((students) => {
            if (students._id === newStudents._id) {
              return newStudents;
            }
            return students;
          });
          setStudentsList(studentsList)
        }
        wx.navigateBack({ delta: 1 });

      })
      .catch((e) => {
        if (e.message !== 'cancel') {
          Toast({
            context: this,
            selector: '#t-toast',
            message: '子女编辑发生错误',
            icon: '',
            duration: 1000,
          });
          wx.navigateBack({ delta: 1 });
        }
      });
  },
  studentsListSort() {
    let studentsList = [...this.data.studentsList];
    studentsList.sort((prevStudent, nextstudent) => {
      if (prevStudent.default == 1 && nextstudent.default != 1) {
        return -1;
      }
      if (prevStudent.default != 1 && nextstudent.default == 1) {
        return 1;
      }
      return 0;
    });

    this.setData({
      studentsList: studentsList,
    });
  }
})